package org.gzc.queue;


/**
 * @Description: 数组队列
 * 缺点就是容易造成空间浪费，多余空间不能被重复利用，需要通过循环队列解决
 * @Author: guozongchao
 * @Date: 2020/8/1 22:36
 */
public class ArrayQueue {
    private int capacity;
    private int[] items;
    private int front;  //指向队列头元素的上一个位置
    private int rear;  //指向队列尾元素的下标

    public ArrayQueue(int capacity) {
        this.items = new int[capacity];
        this.front=-1;
        this.rear=-1;
        this.capacity = capacity;
    }
    //判断队列是否为空
    private boolean isEmpty() {
        return front == rear;
    }

    //判断队列是否满了
    private boolean isFull() {
        return rear == capacity-1;
    }

    //入队
    public void add(int item) {
        if (isFull()) {
            throw new RuntimeException("队列已满，不能添加数据！");
        }
        rear++;
        items[rear]=item;
    }

    //出队
    public int get(){
        if (isEmpty()) {
            throw new RuntimeException("队列为没有数据！");
        }
        front++;
        return items[front];
    }

    //获取队列头部元素，但不出队
    public int getHeadItem() {
        return items[front + 1];
    }

    //显示队列的数据
    public void show() {
        if (isEmpty()) {
            System.out.println("队列为没有数据！");
            return;
        }
        for (int i = front + 1; i <= rear; i++) {
            System.out.printf("第%d个元素为%d\n", i, items[i]);
        }
    }


}
